import getSqliteClient from "@/services/sqlite/init";
import {
    ChatSessionCreate, ChatSessionDeleteType,
    ChatSessionQueryType,
    ChatSession,
    ChatSessionUpdate,
    SessionType
} from "@/types/chat-session";


const client = getSqliteClient()

/**
 * 插入一条会话记录
 */
export async function insertChatSession(session: ChatSessionCreate): Promise<void> {
    await client.runAsync(
        `INSERT INTO chat_session (owner_id, session_id, session_type) VALUES (?, ?, ?)`,
        [
            session.ownerId,
            session.sessionId,
            session.sessionType
        ]
    ).catch(e => console.error("插入会话失败:", e));
}


/**
 * 更新会话记录
 * @param session 会话更新类型
 */
export async function updateChatSession(session: ChatSessionUpdate): Promise<void> {
    const fields: string[] = [];
    const params: any[] = [];

    if (session.sessionType !== undefined) {
        fields.push("session_type = ?");
        params.push(session.sessionType);
    }
    if (session.lastMessageId !== undefined) {
        fields.push("last_message_id = ?");
        params.push(session.lastMessageId);
    }
    if (session.lastMessage !== undefined) {
        fields.push("last_message = ?");
        params.push(session.lastMessage);
    }
    if (session.unreadCount !== undefined) {
        fields.push("unread_count = ?");
        params.push(session.unreadCount);
    }
    if (session.notice !== undefined) {
        fields.push("notice = ?");
        params.push(session.notice);
    }
    if (session.draft !== undefined) {
        fields.push("draft = ?");
        params.push(session.draft);
    }
    if (session.disturb !== undefined) {
        fields.push("disturb = ?");
        params.push(session.disturb);
    }

    if (fields.length === 0) return;

    const sql = `UPDATE chat_session SET ${fields.join(", ")} WHERE session_id = ? AND owner_id = ?`;
    params.push(session.sessionId, session.ownerId);

    await client.runAsync(sql, params).catch(e => console.error("更新会话失败:", e));
}


/**
 * 获取所有会话
 * @param ownerId 拥有者ID
 */
export async function selectChatSessionList(ownerId: string): Promise<ChatSession[]|null> {
    const rows = await client.getAllAsync(
        `SELECT 
             cs.*, 
             CASE 
               WHEN cs.session_type = ${SessionType.SINGLE} THEN u.name 
               WHEN cs.session_type = ${SessionType.GROUP} THEN g.group_name 
             END AS session_name,
             CASE 
               WHEN cs.session_type = ${SessionType.SINGLE} THEN u.avatar 
               WHEN cs.session_type = ${SessionType.GROUP} THEN g.group_avatar 
             END AS session_avatar
           FROM chat_session cs
           LEFT JOIN chat_user u ON cs.session_type = ${SessionType.SINGLE} AND cs.session_id = u.id
           LEFT JOIN group_info g ON cs.session_type = ${SessionType.GROUP} AND cs.session_id = g.group_id
           WHERE cs.owner_id = ?`,
        [ownerId]
    );

    if (!rows) {
        return null
    }
    return rows.map(mapToChatSession);
}


/**
 * 计算所有会话的未读数之和
 * @param ownerId 拥有者ID
 */
export async function countTotalUnreadCount(ownerId: string): Promise<number> {
    const {count} = await client.getFirstAsync<{ count: number }>(
        `SELECT SUM(unread_count) as count FROM chat_session WHERE owner_id = ?`,
        [ownerId]
    );
    return count || 0;
}

/**
 * 根据会话 ID 查询会话记录
 * @param sessionId
 * @param ownerId
 */
export async function getSessionBySessionId({sessionId, ownerId}: ChatSessionQueryType): Promise<ChatSession|null> {
    const row = await client.getFirstAsync<any>(
        `SELECT 
             cs.*, 
             CASE 
               WHEN cs.session_type = ${SessionType.SINGLE} THEN u.name 
               WHEN cs.session_type = ${SessionType.GROUP} THEN g.group_name 
             END AS session_name,
             CASE 
               WHEN cs.session_type = ${SessionType.SINGLE} THEN u.avatar 
               WHEN cs.session_type = ${SessionType.GROUP} THEN g.group_avatar 
             END AS session_avatar
           FROM chat_session cs
          LEFT JOIN chat_user u ON cs.session_type = ${SessionType.SINGLE} AND cs.session_id = u.id
           LEFT JOIN group_info g ON cs.session_type = ${SessionType.GROUP} AND cs.session_id = g.group_id
           WHERE cs.session_id = ? AND cs.owner_id = ?`,
        [sessionId, ownerId]
    );

    if (!row) {
        return null; // 没查到的话返回 null
    }

    return mapToChatSession(row); // 有的话，映射一下
}

/**
 * 删除指定会话
 * @param sessionId 会话ID
 * @param ownerId
 */
export async function deleteChatSession({sessionId, ownerId}: ChatSessionDeleteType): Promise<void> {
    await client.runAsync(`DELETE FROM chat_session WHERE session_id = ? AND owner_id = ?`, [sessionId, ownerId]);
}

/**
 * 批量删除指定会话
 * @param sessionIds 会话ID数组
 * @param ownerId 拥有者ID
 */
export async function deleteBatchSessionsByIds(sessionIds: string[], ownerId: string): Promise<void> {
    const placeholders = sessionIds.map(() => "?").join(", ");
    const params = [...sessionIds, ownerId];
    await client.runAsync(
        `DELETE FROM chat_session WHERE session_id IN (${placeholders}) AND owner_id = ?`,
        params
    ).catch(e => console.error("批量删除会话失败:", e));
}

/**
 * 清除指定用户的所有会话
 * @param ownerId 拥有者ID
 */
export async function clearSession(ownerId: string): Promise<void> {
    await client.runAsync(`DELETE FROM chat_session WHERE owner_id = ?`, [ownerId]);
}

/**
 * 将数据库行映射为 ChatSession
 */
function mapToChatSession(row: any): ChatSession {
    return {
        sessionId: row.session_id,
        sessionAvatar: row.session_avatar,
        sessionName: row.session_name,
        sessionType: row.session_type,
        lastMessageId: row.last_message_id,
        lastMessage: row.last_message,
        unreadCount: row.unread_count,
        disturb: !!row.disturb,
        pined: !!row.pined,
        draft: row.draft,
        notice: !!row.notice,
        updateTime: row.update_time
    };
}
